package com.example.protocol.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 转换bytes字节码的通用工具类
 * 这些二进制转换应该均用的是小端模式（此处存疑，bytesToFloat又似乎是大端）
 */
public class ByteTransfer {
	public static Logger logger = LoggerFactory.getLogger(ByteTransfer.class);

	/**
	 * 4字节byte数组转float
	 * @param b
	 * @return
	 */
	public static float bytesToFloat(byte... b) {
//		logger.trace("transfer to float:" + toHexString(b));
		int accum = 0;
		accum = accum | (b[3] & 0xff) << 0;
		accum = accum | (b[2] & 0xff) << 8;
		accum = accum | (b[1] & 0xff) << 16;
		accum = accum | (b[0] & 0xff) << 24;
		float f = Float.intBitsToFloat(accum);
		//logger.trace("float:"+Float.toString(f));
		return f;
	}

	/**
	 * 2两字节转int
	 * @param high
	 * @param low
	 * @return
	 */
	public static int bytesToInt(byte high, byte low) {
		return ((high & 0xff) << 8 ) + low ;
	}

	/**
	 * 两位bytes转无符号short，
	 * 【特殊说明】java的有short都是有符号的，所以结果需要用int来存，否则像65535就会出错
	 * @return 一个int值
	 */
	public static int bytesToUnsignedShort(byte high, byte low) {
		return (int) ((high & 0xff) << 8) | (low & 0xff);
	}

	public static short bytesToSignedShort(byte high, byte low) {
		return (short) ((high << 8) | (low & 0xFF));
	}

	/**
	 * hex转byte数组
	 * @param hex
	 * @return
	 */
	public static byte[] hexToBytes(String hex){
		int m = 0, n = 0;
		int byteLen = hex.length() / 2; // 每两个字符描述一个字节
		byte[] ret = new byte[byteLen];
		for (int i = 0; i < byteLen; i++) {
			m = i * 2 + 1;
			n = m + 1;
			int intVal = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));
			ret[i] = Byte.valueOf((byte)intVal);	//intVal可以大于127
		}
		return ret;
	}

	public static String bytesToHexString(byte[] bytes) {
		StringBuilder sb = new StringBuilder(bytes.length *2);
		for(byte b:bytes)
		{
			sb.append(String.format("%02x-", b));
		}
		return sb.toString();
	}

	public static String shortToHexString(short si) {
		/*
		StringBuilder sb = new StringBuilder(2 *2);

		sb.append(String.format("0x%04x", si));

		return sb.toString();

		 */
		return String.format("0x%x", si);
	}

	public static String intToHexString(int i){
		return String.format("0x%x",i);
	}

}




